package com.sc.admin.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sc.entity.User;
import com.sc.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * @Author: Sunk 673116067@qq.com
 * @Date: 2018/4/19 16:43
 * @Description:
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final Logger logger= LoggerFactory.getLogger(HandlerInterceptor.class);
    //session中User标识
    private final static String USER="user";
    @Autowired
    IUserService userService;
    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
//         logger.info("requestUri:" + uri);

        if(request.getSession().getAttribute(USER)!=null)
            return true;
        // 不拦截的地址
        String [] uris={"type/getType","users/login","goods/find","users/userInfo","goods/productHome","users/cartList","users/checkOut","goods/computer"
        ,"goods/fingGoodsByKey","goods/getGoods","goods/productDet","ytmall"};
        for(String u:uris){
            if (uri.contains(u)){
                return true;
            }
        }


        if(uri.contains("users/userInfo")) {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(USER)) {
                    if (cookie.getValue() != null) {
                        User u = JSONObject.parseObject(URLDecoder.decode(cookie.getValue(),"utf-8"), User.class);
                        u = userService.selectOne(
                                new EntityWrapper<User>()
                                        .eq("user_account", u.getUserAccount())
                                        .eq("user_password", u.getUserPassword())
                        );
                        if (u != null) {
                            request.getSession().setAttribute(USER, u);
                        }
                    }
                }
            }
            return true;
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户登录验证不正确");
        return false;
    }
    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
